import React, { useState, useEffect } from 'react';
import { Layout, Menu, Button, Badge, Avatar, Tooltip, App } from 'antd';
import { MenuFoldOutlined, MenuUnfoldOutlined, ExclamationCircleOutlined, ReloadOutlined } from '@ant-design/icons';
import { Header } from './Header';
import { ConfigForm } from './ConfigForm';
import { ProjectList } from './ProjectList';
import { ReportGenerator } from './ReportGenerator';
import { ReportGeneratorNew } from './ReportGeneratorNew';
import { ManualReportGenerator } from './ManualReportGenerator';
import { StatusBar } from './StatusBar';
import PathMappingManager from './PathMappingManager';
import { AppConfig, ProjectConfig, AIProvider } from '../types';
import { LocalStorageService } from '../services/LocalStorageService';
import { ConfigService } from '../services/ConfigService';
import ApiService from '../services/ApiService';
import { Settings, FileText, FolderPlus, Edit3, FolderOpen, X, Folder } from 'lucide-react';
import { useToast } from '../contexts/ToastContext';

const { Sider, Content } = Layout;

export const ConfigurationApp: React.FC = () => {
  const [config, setConfig] = useState<AppConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [isDockerEnvironment, setIsDockerEnvironment] = useState(false);
  const { showToast } = useToast();
  const { modal } = App.useApp();

  const [activeTab, setActiveTab] = useState<'config' | 'report' | 'manual' | 'projects' | 'pathMapping'>('config');
  const [selectedProject, setSelectedProject] = useState<ProjectConfig | null>(null);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);


  // 加载配置
  useEffect(() => {
    loadConfiguration();
    loadSelectedProject();
  }, []);



  const loadConfiguration = async () => {
    try {
      setLoading(true);
      
      // 检测Docker环境
      try {
        const response = await fetch('/api/path-mapping/config');
        if (response.ok) {
          const pathMappingData = await response.json();
          if (pathMappingData.success) {
            const isDocker = pathMappingData.data.isDocker;
            setIsDockerEnvironment(isDocker);
            // 如果不是Docker环境且当前选中路径映射选项卡，则切换到配置选项卡
            if (!isDocker && activeTab === 'pathMapping') {
              setActiveTab('config');
            }
          }
        }
      } catch (error) {
        console.warn('无法检测Docker环境，默认为本地环境:', error);
        setIsDockerEnvironment(false);
        // 如果检测失败且当前选中路径映射选项卡，则切换到配置选项卡
        if (activeTab === 'pathMapping') {
          setActiveTab('config');
        }
      }
      
      // 尝试从后端API加载配置和项目数据
      try {
        const backendConfig = await ConfigService.getConfig();
        
        // 从后端API获取项目列表
        const projectsResult = await ApiService.projects.getAll();
        
        let projects = [];
        if (projectsResult.success && projectsResult.data) {
          console.log('[ConfigurationApp] API返回的项目数据:', projectsResult.data);
          // 转换API数据格式
          projects = projectsResult.data.map(p => ({
            id: p.id,
            name: p.name,
            path: p.path,
            description: p.description || '',
            addedAt: p.createdAt || p.addedAt || new Date().toISOString()
          }));
          
          console.log('[ConfigurationApp] 转换后的项目数据:', projects);
          
          // 同步到本地存储
          LocalStorageService.saveProjects(projects);
        } else {
          console.warn('[ConfigurationApp] API获取项目失败，使用本地存储:', projectsResult.error);
          // API失败时使用本地存储的项目数据
          projects = LocalStorageService.getProjects();
        }
        
        const configWithProjects = { ...backendConfig, projects };
        console.log('[ConfigurationApp] 设置配置状态:', configWithProjects);
        setConfig(configWithProjects);
        return;
      } catch (apiError) {
        console.warn('后端API不可用，使用本地存储:', apiError);
      }
      
      // 后端API不可用时，回退到本地存储
      const result = LocalStorageService.loadConfig();
      
      if (result.success && result.data) {
        // 同步项目数据
        const projects = LocalStorageService.getProjects();
        const configWithProjects = { ...result.data, projects };
        setConfig(configWithProjects);
      } else {
        const defaultConfig = LocalStorageService.getDefaultConfig();
        // 同步项目数据
        const projects = LocalStorageService.getProjects();
        const configWithProjects = { ...defaultConfig, projects };
        setConfig(configWithProjects);
        LocalStorageService.saveConfig(configWithProjects);
      }
    } catch (error) {
      showMessage('error', `加载配置失败: ${error}`);
      const defaultConfig = LocalStorageService.getDefaultConfig();
      // 同步项目数据
      const projects = LocalStorageService.getProjects();
      const configWithProjects = { ...defaultConfig, projects };
      setConfig(configWithProjects);
    } finally {
      setLoading(false);
    }
  };

  const loadSelectedProject = () => {
    const project = LocalStorageService.getSelectedProject();
    setSelectedProject(project);
  };



  const saveConfiguration = async (newConfig: AppConfig) => {
    try {
      setSaving(true);
      
      // 尝试保存到后端API
      try {
        await ConfigService.saveConfig(newConfig);
        setConfig(newConfig);
        showMessage('success', '配置保存成功！');
        return;
      } catch (apiError) {
        console.warn('后端API不可用，使用本地存储:', apiError);
      }
      
      // 后端API不可用时，回退到本地存储
      const result = LocalStorageService.saveConfig(newConfig);
      
      if (result.success) {
        setConfig(newConfig);
        showMessage('success', '配置保存成功（本地存储）！');
      } else {
        showMessage('error', `保存配置失败: ${result.error}`);
      }
    } catch (error) {
      showMessage('error', `保存配置失败: ${error}`);
    } finally {
      setSaving(false);
    }
  };

  const addProject = async (projectPath: string, projectName: string) => {
    try {
      // 尝试通过API添加项目
      try {
        const result = await ApiService.projects.add(projectName, projectPath, '');
        
        if (result.success && result.data) {
          // 直接更新本地状态，不重新加载整个配置
          setConfig(prevConfig => ({
            ...prevConfig!,
            projects: [...(prevConfig!.projects || []), result.data!]
          }));
          
          showMessage('success', '项目添加成功！');
          return true;
        } else {
          showMessage('error', `添加项目失败: ${result.error}`);
          return false;
        }
      } catch (apiError) {
        console.warn('API添加项目失败，使用本地存储:', apiError);
        
        // API失败时回退到本地存储
        const result = await LocalStorageService.addProject(projectPath, projectName);
        
        if (result.success && result.data) {
          // 直接更新本地状态，不重新加载整个配置
          setConfig(prevConfig => ({
            ...prevConfig!,
            projects: [...(prevConfig!.projects || []), result.data!]
          }));
          
          showMessage('success', '项目添加成功（本地存储）！');
          return true;
        } else {
          showMessage('error', `添加项目失败: ${result.error}`);
          return false;
        }
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      showMessage('error', `添加项目失败: ${errorMessage}`);
      return false;
    }
  };

  const showDeleteDialog = (projectId: string, projectName: string) => {
    modal.confirm({
      title: '删除项目',
      content: `确定要删除项目 "${projectName}" 吗？此操作不可撤销。`,
      icon: React.createElement(ExclamationCircleOutlined),
      okText: '确认删除',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        await handleDeleteConfirm(projectId);
      }
    });
  };

  const handleRemoveProject = async (projectId: string) => {
    // 直接执行删除，因为ProjectList组件已经处理了确认对话框
    await handleDeleteConfirm(projectId);
  };

  const handleDeleteConfirm = async (projectId: string) => {
    try {
      // 尝试通过API删除项目
      try {
        const result = await ApiService.projects.remove(projectId);
        
        if (result.success) {
          // 如果删除的是当前选中的项目，清除选中状态
          if (selectedProject && selectedProject.id === projectId) {
            setSelectedProject(null);
            LocalStorageService.setSelectedProject(null);
          }
          
          // 直接更新本地状态，不重新加载整个配置
          setConfig(prevConfig => ({
            ...prevConfig!,
            projects: prevConfig!.projects?.filter(p => p.id !== projectId) || []
          }));
          
          showMessage('success', '项目删除成功！');
        } else {
          showMessage('error', `删除项目失败: ${result.error}`);
        }
      } catch (apiError) {
        console.warn('API删除项目失败，使用本地存储:', apiError);
        
        // API失败时回退到本地存储
        const result = await LocalStorageService.removeProject(projectId);
        
        if (result.success) {
          // 如果删除的是当前选中的项目，清除选中状态
          if (selectedProject && selectedProject.id === projectId) {
            setSelectedProject(null);
            LocalStorageService.setSelectedProject(null);
          }
          
          // 直接更新本地状态，不重新加载整个配置
          setConfig(prevConfig => ({
            ...prevConfig!,
            projects: prevConfig!.projects?.filter(p => p.id !== projectId) || []
          }));
          
          showMessage('success', '项目删除成功（本地存储）！');
        } else {
          showMessage('error', `删除项目失败: ${result.error}`);
        }
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      showMessage('error', `删除项目失败: ${errorMessage}`);
    }
  };

  const selectProject = (project: ProjectConfig) => {
    console.log('[ConfigurationApp] selectProject 接收到的项目对象:', project);
    console.log('[ConfigurationApp] 项目对象类型:', typeof project);
    console.log('[ConfigurationApp] 项目路径:', project.path);
    console.log('[ConfigurationApp] 项目路径类型:', typeof project.path);
    
    setSelectedProject(project);
    LocalStorageService.setSelectedProject(project);
    showMessage('success', `已选择项目: ${project.name}`);
  };



  const showMessage = (type: 'success' | 'error', text: string) => {
    showToast({ type, text });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gradient-to-br from-neutral-50 to-primary-50">
        <div className="text-center p-8 bg-white rounded-3xl shadow-strong border border-neutral-200">
          <div className="animate-spin rounded-full h-16 w-16 border-4 border-primary-200 border-t-primary-600 mx-auto mb-6"></div>
          <h3 className="text-lg font-semibold text-neutral-800 mb-2">加载配置中</h3>
          <p className="text-neutral-600">请稍候，正在初始化系统...</p>
        </div>
      </div>
    );
  }

  if (!config) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-gradient-to-br from-neutral-50 to-error-50">
        <div className="text-center p-8 bg-white rounded-3xl shadow-strong border border-error-200">
          <div className="w-16 h-16 bg-error-100 rounded-full flex items-center justify-center mx-auto mb-6">
            <svg className="w-8 h-8 text-error-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
            </svg>
          </div>
          <h3 className="text-lg font-semibold text-error-800 mb-2">配置加载失败</h3>
          <p className="text-error-600 mb-6">系统无法加载配置文件，请重试</p>
          <button 
            onClick={loadConfiguration}
            className="px-6 py-3 bg-gradient-to-r from-primary-600 to-primary-700 text-white rounded-xl hover:from-primary-700 hover:to-primary-800 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 transition-all duration-200 font-medium shadow-medium"
          >
            重新加载
          </button>
        </div>
      </div>
    );
  }

  // 菜单项配置
  const menuItems = [
    {
      key: 'config',
      icon: <Settings className="h-4 w-4" />,
      label: '系统配置',
      description: '基础设置'
    },
    {
      key: 'report',
      icon: <FileText className="h-4 w-4" />,
      label: '生成报告',
      description: '智能分析'
    },
    {
      key: 'manual',
      icon: <Edit3 className="h-4 w-4" />,
      label: '手动报告',
      description: '文字输入'
    },
    {
      key: 'projects',
      icon: <FolderPlus className="h-4 w-4" />,
      label: '项目管理',
      description: '仓库配置'
    },
    ...(isDockerEnvironment ? [{
      key: 'pathMapping',
      icon: <FolderOpen className="h-4 w-4" />,
      label: '路径映射',
      description: 'Docker配置'
    }] : [])
  ];

  return (
    <div className="h-screen bg-gray-50">
      <Header />
      
      <Layout className="h-[calc(100vh-64px)]">
        {/* 左侧边栏 */}
        <Sider 
          width={320} 
          className="bg-white border-r border-neutral-200 shadow-sm"
          collapsible
          collapsed={sidebarCollapsed}
          onCollapse={(collapsed) => setSidebarCollapsed(collapsed)}
          trigger={null}
          breakpoint="lg"
          collapsedWidth={80}
        >
          <div className="h-full flex flex-col">
            {/* 折叠菜单按钮 - 移到顶部 */}
            <div className="border-b border-gray-100 p-2">
              <Button
                type="text"
                icon={sidebarCollapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
                className="w-full text-gray-400 hover:text-gray-600 hover:bg-gray-50 border-none text-xs"
                size="small"
              />
            </div>
            {/* 当前工作项目显示 */}
            {selectedProject && (
              <div className={`border-b border-neutral-200 bg-gray-50 ${
                sidebarCollapsed ? 'p-2' : 'p-4'
              }`}>
                <div className={`flex items-center ${
                  sidebarCollapsed ? 'justify-center' : 'space-x-3'
                }`}>
                  <div className="relative">
                    <Avatar 
                      size={sidebarCollapsed ? 32 : 40}
                      icon={<Folder className={sidebarCollapsed ? 'h-4 w-4' : 'h-5 w-5'} />}
                      className="bg-blue-500"
                    />
                    <Badge 
                      status="success" 
                      className="absolute -top-1 -right-1"
                    />
                  </div>
                  {!sidebarCollapsed && (
                    <>
                      <div className="flex-1 min-w-0">
                        <div className="text-xs font-semibold text-gray-800 mb-1">当前项目</div>
                        <Tooltip title={selectedProject.name}>
                          <div className="text-sm font-semibold text-gray-900 truncate">
                            {selectedProject.name}
                          </div>
                        </Tooltip>
                      </div>
                      <Button 
                        type="text" 
                        size="small"
                        icon={<X className="h-3 w-3" />}
                        onClick={() => {
                          setSelectedProject(null);
                          LocalStorageService.setSelectedProject(null);
                        }}
                        className="text-gray-600 hover:text-gray-800 hover:bg-gray-100"
                      />
                    </>
                  )}
                </div>
                {sidebarCollapsed && (
                  <Tooltip title={`当前项目: ${selectedProject.name}`} placement="right">
                    <div className="w-full h-1 bg-blue-500 rounded-full mt-2"></div>
                  </Tooltip>
                )}
              </div>
            )}
            
            {/* 菜单导航 */}
            <div className={`flex-1 ${sidebarCollapsed ? 'p-2' : 'p-4'}`}>
              <div className="space-y-2">
                {menuItems.map((item) => (
                  <Tooltip key={item.key} title={sidebarCollapsed ? item.label : ''} placement="right">
                    <button
                      onClick={() => setActiveTab(item.key as any)}
                      className={`w-full flex items-center transition-all duration-200 text-left rounded-xl ${
                        sidebarCollapsed 
                          ? 'justify-center p-2' 
                          : 'space-x-3 p-3'
                      } ${
                        activeTab === item.key
                          ? 'bg-blue-500 text-white shadow-md transform scale-105'
                          : 'text-neutral-700 hover:bg-neutral-100 hover:text-blue-600 hover:scale-102'
                      }`}
                    >
                      <div className={`rounded-lg transition-all duration-200 ${
                        sidebarCollapsed ? 'p-2' : 'p-2'
                      } ${
                        activeTab === item.key 
                          ? 'bg-white/20 text-white' 
                          : 'bg-neutral-100 text-neutral-500'
                      }`}>
                        {item.icon}
                      </div>
                      {!sidebarCollapsed && (
                        <div className="flex-1">
                          <div className="font-semibold text-sm">{item.label}</div>
                          <div className={`text-xs opacity-70 ${
                            activeTab === item.key ? 'text-white/80' : 'text-neutral-500'
                          }`}>
                            {item.description}
                          </div>
                        </div>
                      )}
                    </button>
                  </Tooltip>
                ))}
              </div>
            </div>
          </div>
        </Sider>
        
        {/* 主内容区域 */}
        <Content className="flex-1 overflow-auto">
          <div className="h-full p-4">
            {/* 标签页内容 */}
            {activeTab === 'config' ? (
              /* 系统配置 */
              <ConfigForm 
                config={config}
                onSave={saveConfiguration}
                saving={saving}
              />
            ) : activeTab === 'report' ? (
              /* 报告生成 */
              <ReportGeneratorNew 
                selectedProject={selectedProject}
              />
            ) : activeTab === 'manual' ? (
              /* 手动报告 */
              <ManualReportGenerator 
                selectedProject={null}
                config={config}
              />
            ) : activeTab === 'pathMapping' ? (
              /* 路径映射管理 */
              <div className="bg-white rounded-3xl shadow-medium border border-neutral-200">
                <div className="bg-gray-50 px-8 py-6 border-b border-neutral-200 rounded-t-3xl">
                  <div className="flex items-center space-x-4">
                    <div className="w-12 h-12 bg-blue-500 rounded-2xl flex items-center justify-center shadow-medium">
                      <FolderOpen className="w-6 h-6 text-white" />
                    </div>
                    <div>
                      <h2 className="text-3xl font-bold text-neutral-900">路径映射管理</h2>
                      <p className="text-neutral-600 mt-1 font-medium">配置Docker容器与宿主机的路径映射关系</p>
                    </div>
                  </div>
                </div>
                <PathMappingManager />
              </div>
            ) : (
              /* 项目管理 */
              <div className="space-y-8">
                <div className="bg-white rounded-3xl shadow-medium border border-neutral-200 p-8">
                  <div className="flex items-center justify-between mb-6">
                    <div className="flex items-center space-x-4">
                      <div className="w-12 h-12 bg-blue-500 rounded-2xl flex items-center justify-center shadow-medium">
                        <FolderPlus className="w-6 h-6 text-white" />
                      </div>
                      <div>
                        <h2 className="text-3xl font-bold text-neutral-900">项目管理</h2>
                        <p className="text-neutral-600 mt-1 font-medium">管理您要生成报告的Git项目</p>
                      </div>
                    </div>
                    <Button
                      type="default"
                      icon={<ReloadOutlined />}
                      onClick={async () => {
                        try {
                          // 重新获取项目列表，只更新项目数据
                          const result = await ApiService.projects.getAll();
                          if (result.success && result.data) {
                            setConfig(prevConfig => ({
                              ...prevConfig!,
                              projects: result.data!
                            }));
                            showMessage('success', '项目列表已刷新！');
                          } else {
                            // API失败时回退到完整重新加载
                            await loadConfiguration();
                          }
                        } catch (error) {
                          // 出错时回退到完整重新加载
                          await loadConfiguration();
                        }
                      }}
                      title="刷新列表"
                    />
                  </div>
                  <ProjectList 
                    projects={config.projects || []}
                    onAddProject={addProject}
                    onRemoveProject={handleRemoveProject}
                    onSelectProject={selectProject}
                  />
                </div>
              </div>
            )}
          </div>
        </Content>
      </Layout>

      <StatusBar configPath="浏览器本地存储" />
    </div>
  );
};